package Logic

import (
	"fmt"
	"yz-go/Common"
	"yz-go/Models"

	"github.com/gin-gonic/gin"
)

type CateList struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

func CategoryLogic(page int, size int, uid any, ust bool, c *gin.Context) (rd Common.ResData) {

	// var CateList []CateList
	// CateList := &CateList{}
	CateList := []CateList{}

	// 用户的期望分类
	var UCateIds []int64
	mobile := "17321295203"

	field := "id, `name`"

	query := Models.DB.Table("recruit_position_category")
	if ust {
		Common.Err = Models.DB.Table("recruit_notes_intention").Where("`mobile` = ? and status = ?", mobile, 1).Select("position_category_id").Find(&UCateIds).Error
		Common.Err = query.Where("`id` in ? and status = ?", UCateIds, 1).Find(&CateList).Error
	} else {
		Common.Err = query.Where("status = ?", 1).Select(field).Find(&CateList).Error
	}

	fmt.Printf("ids: %#v", UCateIds)

	fmt.Printf("分类列表：%#v", CateList)

	return Common.ResData{Common.SUCCESS, "", CateList}
}

// 分类树形结构
type CTree struct {
	Id       int64   `json:"id"`
	Name     string  `json:"name"`
	Pid      int64   `json:"pid"`
	Children []CTree `json:"children,omitempty"`
}

func Tree() []CTree {
	cates := Models.GetCate()

	fmt.Printf("所有可用分类：%#v\n", cates)
	res := buildTree(cates)
	return res
}

// public function getMenuTree(array $menus)
// {
// 	$data = [];
// 	foreach ($menus as $menu) {
// 		if ($menu['pid'] === 0) {
// 			$data[] = $this->getChildren($menus, $menu);
// 		}
// 	}

// 	return $data;
// }

// public function getChildren($menus, $menu)
// {
// 	$c = [];
// 	foreach ($menus as $children) {
// 		if ($menu['id'] === $children['pid']) {
// 			$c[] = $this->getChildren($menus, $children);
// 		}
// 	}
// 	$menu['children'] = $c;
// 	$menu['api'] = $this->formatApi($menu['api']);

//		return $menu;
//	}
func buildTree(cates []Models.RecruitPositionCategory) []CTree {
	CNode := []CTree{} // var CNode []CTree
	for _, v := range cates {
		if v.Pid == 0 {
			CNode = buildChecnTree(cates, v)
			nn := CTree{
				Id:       v.Id,
				Pid:      v.Pid,
				Name:     v.Name,
				Children: CNode,
			}
			CNode = append(CNode, nn)
		}
	}
	return CNode
}

// 获取子类
func buildChecnTree(cates []Models.RecruitPositionCategory, cate Models.RecruitPositionCategory) []CTree {
	ChendNode := []CTree{}

	for _, children := range cates {
		if children.Pid == cate.Id {
			cd := buildChecnTree(cates, children)
			node := CTree{
				Id:       children.Id,
				Pid:      children.Pid,
				Name:     children.Name,
				Children: cd,
			}
			ChendNode = append(ChendNode, node)
		}
	}
	return ChendNode
}
